<?php


namespace app\api\controller;


use app\admin\model\pay\Merchant;
use app\admin\model\Recharge;
use app\common\controller\Api;
use app\common\model\AgentShare;
use app\common\model\BillLog;
use app\common\model\RechargeBill;
use app\common\model\RechargeFenConfig;
use app\common\model\Reword;
use app\common\model\User5g;
use think\Db;
use think\exception\HttpException;
use xingwu\Xingwu;

class Mine extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function demo2()
    {
        //update recharge set is_check = 0 where is_check = 1
        //8293.32
        //5208.12
        $map = [
            //"user_id" => $user_id,
            "status" => 1,
            //'is_check' => 0,
            //"is_fen" => ['in',[0,1]],
            'isNeedShare' => 1,
        ];
        $list = Db::table('recharge')
            ->where($map)
            ->whereNotNull('chnltrxid')
            ->whereNotNull('mchId')
            //->where('createtime','<',$end)
            ->order('id desc')
            ->select();
        $i=0;
        foreach($list as $v){
            AgentShare::checkFenMoney2($v['mchId'],$v['chnltrxid']);
            $i++;
        }
        echo $i.PHP_EOL;
        $map = [
            'isNeedShare' => 1,
        ];
        $check_amount = Db::table('recharge')
            ->where($map)
            ->whereNotNull('chnltrxid')
            ->whereNotNull('mchId')
            ->where('check_amount','>',0)
            //->limit(100)
            ->sum('check_amount');
        echo $check_amount.PHP_EOL;die();
        die();
    }

    public function demo()
    {
        $user = \app\common\model\User::get(12529);
        User5g::reg5gUser($user);
       /*  $row = AgentShare::findFenMoney('39497568','M20221122801897529553842177');
         echo $row;*/
        //Reword::getOrder();
        //Reword::batchSend();
        //Reword::batchCheck();
        //Reword::checkMoney();
      /*  Reword::getOrder();
        Reword::batchSend();*/
        //Reword::batchCheck();
        //Reword::checkFenStatus();

       // Reword::checkFenStatus();
        //Reword::batchCheck();
       /* $order_sn = input('order_sn');
        if($order_sn){
            Reword::getOrder($order_sn);
        }*/
        //Reword::batchFen('202208565148970020153000');
       /* $order = Db::table('shopro_order_bill')->find(2381);
        die();*/
        //Reword::preLog2($order);
    }

    public function test()
    {
        /*
         * Array
(
    [mchId] => 39497568
    [mchSharingNo] => F2022111657501011
    [transactionId] => M20221115799342618114510848
    [totalAmount] => 7
    [receivers] => [{"receiverId":"39770630","receiverType":"B","amount":7,"description":"fen"}]
)
Array
(
    [code] => 600
    [msg] => 分账接收方非法
    [data] =>
    [nonceStr] => cae7e0dde7749b2edeb3f7464fc8f1b0
)
*/
        //AgentShare::bindAccount('39497568','39770630');
        $data = BillLog::get(247);
        AgentShare::sendFen($data);
        /*die();
        $h = date('H');
        if($h >= 1 && $h < 2){

        }
        $h = date('H');
        if($h >= 2 && $h < 3){

        }
        die();
        $data = BillLog::get(235);
        //AgentShare::sendFen($data);
        $row = AgentShare::checkFen($data);*/

        die();
        //查询分账余额
       /* $row = AgentShare::findFenMoney('39497568','M20221115799314366096461825');
        echo $row;
        die();*/
        // 查询分账余额
        //$row = AgentShare::requestJavaAPIV2($url,$option); //已调通*/
        //print_r($row);
        //die();
        //die();
        $url = 'https://pay.51wanquan.com/api/sharing/receiver/bind';
        $arr = ["receiverType"=>"B","receiverId" => "1931912769"];
        $arr = ["receiverType"=>"B","receiverId" => "39753997"];
        //$receiver = json_encode($arr,JSON_UNESCAPED_UNICODE);
        $receiver=$arr;
        $option = [
            "mchId" => '39497568',
            "receiver" => json_encode($receiver,true,JSON_UNESCAPED_UNICODE),//receiverId 读取  fz_number
            // "receiver" => $arr,//receiverId 读取  fz_number
        ];
        //print_r($option);die();
        // 添加分账接收方
        $row = AgentShare::requestJavaAPIV2($url,$option);   //维护绑定关系表
        print_r($row);
        die();

        //分账
        $fenUrl = 'https://pay.51wanquan.com/api/sharing';

        $option = [
            "mchId" => '39497568', //Excel第三列
            "mchSharingNo" => '', //自己生成的分账流水号
            "transactionId" => 'M20221115799314366096461825', //M开头
            "totalAmount" => '',  // 下面列表的总和。
            "receivers" => [
                ['receiverId' => '','receiverType'=>"",'amount'=>'',"description"=>""]// 最多5个
            ],
        ];
        //只分钱包类型的
        AgentShare::requestJavaAPIV2($fenUrl,$option);
        // 有分账 查询接口
        /**
         *https://pay.51wanquan.com/api/sharing/inquiry
         *   "status": "FINISHED", 代表请求完成
         * "sharingStatus":"SUCCESS" 代表的是分账成功
         */
    }

    protected function exec($api,$json)
    {
        $res = ['code'=>0,'msg'=>''];
        $config = config('thirdpay.xingwu');
        /*$this->mchid = $config['mchid'];
        $this->signKey = $config['signKey'];
        $this->host = $config['host'];*/
        //echo $config['signKey'];
        try {
            $param = $this->sign($json,$config['signKey']);
        } catch (HttpException $e) {
            $res['msg'] = $e->getMessage();
            return $res;
        }
        //echo $param.PHP_EOL;die();
        $httpRes = $this->curl_post($api,$param);
        if (empty($httpRes[0])) {
            $res['msg'] = '请求支付失败';
            return $res;
        }
        $arr = json_decode($httpRes[0],true);
        $res['data'] = $arr;
        print_r($res);die();
        // var_dump($arr);exit;
        if ($arr['status'] != 'SUCCESS') {
            $res['msg'] = $arr['errMsg'];
            return $res;
        }
        return ['code'=>1,'msg'=>'','data'=>$arr];
    }
    protected function curl_post($url,$uriParam)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 使用命令不执行
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        // curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($uriParam)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_POSTFIELDS,is_array($uriParam)? http_build_query($uriParam):$uriParam); // Post提交的数据包
        // curl_setopt($curl, CURLOPT_POSTFIELDS,$uriParam); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        // curl_setopt($curl, CURLOPT_HTTPHEADER,['Content-type:application/json']); // 设置头部
        curl_setopt($curl, CURLOPT_HTTPHEADER,['Content-type:application/x-www-form-urlencoded']); // 设置头部
        $res = curl_exec($curl); // 执行操作
        $errno = curl_errno($curl);
        curl_close($curl); // 关闭CURL会话
        return [$res,$errno];
    }

    public function sign2($parmas,$signKey)
    {
        $signStr = '';
        ksort($params);
        foreach ($params as $key => $val) {
            if ($val === '' || $val === null || is_array($val)) {
                continue;
            }
            $signStr .= ($signStr ? '&' : '') . "{$key}={$val}";
        }
        $signStrWithKey = $signStr . '&key=' . $signKey;
        $signHash = md5($signStrWithKey);
        return $signHash;

        $string = $signStr.'&sign='.strtoupper($signHash);
        return $string;
    }

    protected function sign(array $params, string $signKey): string {
        $signStr = '';
        ksort($params);
        foreach ($params as $key => $val) {
            if ($val === '' || $val === null || is_array($val)) {
                continue;
            }
            $signStr .= ($signStr ? '&' : '') . "{$key}={$val}";
        }
        $signStrWithKey = $signStr . '&key=' . $signKey;
        $signHash = md5($signStrWithKey);
        $string = $signStr.'&sign='.strtoupper($signHash);
        return $string;
    }

    //$res = (new Xingwu)->mini_program_pay($merchant['token'], $total_fee, $order_sn, url('api/pay/notify', '', '', true),$appid,$openid);

    //print_r($row);
    // //  添加分账接收方
    /* $url = 'https://pay.51wanquan.com/api/sharing/receiver/bind';
     $option = [
         'channel' => 'MINI',
         'nonceStr' => uniqid(),
         'timestamp' => time(),
         //'sign' => '',
     ];*/
    //echo func_ascii($option);

    /* $url = 'https://pay.51wanquan.com/api/sharing';
     $optin = [
         ''
     ];
     postRequest($url);*/

}
